<template>
  <div class="orderConfirm">
    <!-- 顶部导航栏 -->
    <van-sticky :offset-top="0">
      <van-nav-bar
        title="订单确认"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </van-sticky>
    <!-- 地址卡片 -->
    <div class="addressCard" @click="showAddress = true">
      <p>服务地址</p>
      <div v-if="selectAddress">
        <div>姓名：{{ selectAddress.name }} 电话：{{ selectAddress.tel }}</div>
        <div>地址：{{ selectAddress.address }}</div>
      </div>
      <div v-else>
        <div>
          姓名：{{ defaultAddress.username }} 电话：{{
            defaultAddress.telephone
          }}
        </div>
        <div>
          地址：{{
            defaultAddress.province +
            defaultAddress.city +
            defaultAddress.area +
            defaultAddress.address
          }}
        </div>
      </div>
    </div>
    <!-- 订单详情卡片 -->
    <div class="orderDetail">
      <p>订单详情</p>
      <div>
        <van-row
          v-for="(item, index) in Array.from(orderLines.values())"
          :key="index"
          type="flex"
          justify="center"
        >
          <van-col span="6">{{ item.productName }}</van-col>
          <van-col span="6">￥{{ item.price }}</van-col>
          <van-col span="6">X{{ item.number }}</van-col>
        </van-row>
        <div style="text-align: right">总计：￥{{ total }}</div>
      </div>
    </div>
    <!-- 服务时间卡片 -->
    <div class="orderTimeCard" @click="showTime = true">
      <div>
        服务时间 <span>{{ timeValue | dateFormat }}</span>
      </div>
    </div>
    <!-- 提交按钮 -->
    <div class="confirm_btn" @click="confirm">确认提交</div>
    <!-- 地址列表弹出框 -->
    <van-popup v-model="showAddress" position="bottom" closeable round>
      <van-address-list
        v-model="chosenAddressId"
        :list="addressList"
        default-tag-text="默认"
        @select="addressSelectHandler"
        add-button-text="确认选择"
        @add="showAddress = false"
      />
    </van-popup>
    <!-- 服务时间选择模态框 -->
    <van-popup v-model="showTime" position="bottom" round>
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showTime = false"
        @confirm="confirmServerTimeHandler"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters, mapMutations } from "vuex";
import { post_json } from "@/http/axios";
import { Notify } from "vant";
export default {
  data() {
    return {
      // 选择的时间
      timeValue: new Date().getTime(),
      // 当前时间
      currentDate: new Date(),
      // 日期选择器显示控制
      showTime: false,
      // 被选中的地址id
      chosenAddressId: "1",
      // 地址面板弹出控制
      showAddress: false,
      // 充值框弹出
      balanceShow: false,
      // 充值金额
      balance: "",
      // 选择的地址
      selectAddress: null,
      minDate: new Date(),
      maxDate: new Date(
        new Date().getFullYear(),
        new Date().getMonth() + 1,
        new Date().getDate()
      ),
      defaultAddress: {},
    };
  },
  created() {
    // 获取用户信息
    this.getUserInfo().then((res) => {
      // 获取地址信息  并设置默认地址
      this.findAddressByUserId(res.data.data.id).then((res) => {
        let address = res.data.data.list;
        let result = address.filter((item) => item.isDefault == 1);
        this.chosenAddressId = result[0].id;
        this.defaultAddress = result[0];
      });
    });
  },
  computed: {
    // 获取保存的订单信息
    ...mapState("shopcart", ["orderLines"]),
    // 获取订单总价
    ...mapGetters("shopcart", ["total"]),
    // 获取地址列表
    ...mapState("address", ["address"]),
    // 获取用户信息
    ...mapState("user", ["userInfo"]),
    // 筛选用户的默认地址

    // 根据地址数据生成匹配组件的地址数据
    addressList() {
      // 筛选地址数据 生成匹配组件的数据
      let addressOld = this.address;
      let addressNew = [];
      if (!addressOld) {
        return;
      }
      addressOld.forEach((item, index) => {
        let obj = {};
        (obj.id = item.id),
          (obj.name = item.username),
          (obj.tel = item.telephone),
          (obj.address = item.province + item.city + item.area + item.address),
          (obj.isDefault = Boolean(item.isDefault));
        addressNew.push(obj);
      });
      return addressNew;
    },
  },
  methods: {
    // 获取地址数据
    ...mapActions("address", ["findAddressByUserId"]),
    // 获取用户信息
    ...mapActions("user", ["getUserInfo"]),
    // 余额充值
    ...mapActions("recharge", ["getRecharge"]),
    // 清空购物车
    ...mapMutations("shopcart", ["clearShopCar"]),
    // 切换地址列表选项
    addressSelectHandler(item) {
      this.selectAddress = item;
    },
    // 确定服务时间回调
    confirmServerTimeHandler(value) {
      // 将时间选择器选中的实践，赋值给时间显示卡片
      this.timeValue = value.getTime();
      // 关闭时间选择器的弹出框
      this.showTime = false;
    },
    // 提交订单
    confirm() {
      let orderData = {
        addressId: this.chosenAddressId,
        customerId: this.userInfo.id,
        serviceTime: this.timeValue,
        orderLines: Array.from(this.orderLines.values()),
      };
      // 将重组数据，保存到数据库
      post_json("/order/submitOrder", orderData).then((res) => {
        if (res.data.status == 200) {
          // 提示成功信息
          Notify({ type: "success", message: "预约成功" });
          // 清空购物车
          this.clearShopCar();
        } else {
          Notify({ type: "danger", message: res.data.message });
        }
      });
    },
    // 充值金额校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      if (val < 0 || val > 1000) {
        return false;
      } else {
        return true;
      }
    },
    // 充值
    topUp() {
      console.log(this.balance, this.userInfo.id);
      let data = {
        customerId: this.userInfo.id,
        money: this.balance,
      };
      this.getRecharge(data).then((r) => {
        console.log(r);
        if (r.data.status == 200) {
          this.$notify({
            type: "success",
            message: r.data.message,
          });
          this.balanceShow = false;
        } else {
          this.$notify({
            type: "danger",
            message: r.data.message,
          });
        }
      });
      // 实现充值逻辑
    },
    // 取消弹框
    toClose() {
      // 余额置空
      this.balance = "";
    },
    // 返回上一级页面
    onClickLeft() {
      this.$router.go(-1);
      console.log();
      setTimeout(() => {
        this.$store.state.shopcart.orderLines.clear();
      }, 500);
    },
  },
};
</script>

<style scoped>
/* 提交按钮 */
.confirm_btn {
  width: 53%;
  height: 40px;
  background-image: linear-gradient(to right, #7579ff, #bf73ff);
  text-align: center;
  color: #fff;
  border-radius: 22px;
  line-height: 40px;
  margin: 0 auto;
  margin-top: 2em;
  cursor: pointer;
}
.van-icon-edit {
  display: none;
}
/* 充值 */
.cz {
  height: 80px;
  text-align: center;
}
.addressCard,
.orderDetail,
.orderTimeCard {
  margin: 1em;
  padding: 10px;
  box-shadow: 0 0 5px 5px rgba(102, 102, 102, 0.294);
}
</style>